<script setup>
  import { Delete, Edit } from '@element-plus/icons-vue'
  import { ref,computed } from 'vue';
  import ViewCourse from '@/components/shared/ViewCourse.vue'
  import { getCourseListService, courseDelService } from '@/api/user'
  const loading = ref(false)
  const drawer = ref()
  const pageSize =ref(15)
  const currentPage=ref(1)
  const openDrawer = () => {
    drawer.value.open({})
  }
  const onEdit = (row) => {
    drawer.value.open(row)

  }

  const courseData = ref([])
  const getCourseList = async () => {
    loading.value = true
    const res = await getCourseListService()
    courseData.value = res.data.course
    loading.value = false
  }
  getCourseList()

  const paginatedData= computed(() => {
    const start = (currentPage.value - 1) * pageSize.value;
    const end = start + pageSize.value;
    return courseData.value.slice(start, end);
});


  const onDel = async (row) => {
    await ElMessageBox.confirm('你确认删除该课程信息吗？', '温馨提示', {
      type: 'warning',
      confirmButtonText: '确认',
      cancelButtonText: '取消'
    })
    await courseDelService(row._id)
    ElMessage({ type: 'success', message: '删除成功' })
    getCourseList()
  }

  const onSuccess = () => {
    getCourseList()
  }

  const handlePageChange=(pageNum) =>{
  currentPage.value=pageNum
  getCourseList()

  }
  const handleSizeChange=(size) =>{
      pageSize.value = size;
      getCourseList()
    }

</script>

<template>
  <page-container title="课程管理">
    <template #extra>
      <el-button type="primary" @click="openDrawer">添加课程</el-button>
    </template>
    <el-table :data="paginatedData" style="width: 100%" v-loading="loading">
      <el-table-column label="课程名称" prop="name"></el-table-column>
      <el-table-column label="学分" prop="credit"></el-table-column>
      <el-table-column label="上课时间" prop="time"></el-table-column>
      <el-table-column label="上课地点" prop="room"></el-table-column>
      <el-table-column label="学期" prop="term"></el-table-column>
      <el-table-column label="操作" width="150">
        <template #default="{ row }">
          <el-button size="small" @click="onEdit(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="onDel(row)">删除</el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>
    <el-pagination background layout="total,prev, pager, next" :total="courseData.length" :page-size="pageSize" @current-change="handlePageChange"  @size-change="handleSizeChange" :current-page="currentPage"
     style="margin-top: 20px; justify-content: flex-end" />
    <view-course ref="drawer" @success="onSuccess"></view-course>
  </page-container>

</template>

<style scoped>
  
</style>